﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.IO;

namespace SalaryChannel.Web
{
    [ServiceContract(Namespace = "http://salary.yangchao.ts.gs.chinamobile/")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class PSSService : ServiceAuthRoot
    {
        #region 创建订单

        [OperationContract]
        public List<string> GetProvider()
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from q in context.PSS_Provider
                                where q.Is_Enable == '1'
                                orderby q.Provider_ID
                                select new { id = q.Provider_ID, name = q.Provider_Name };
                   List<string> ret=  new List<string>();
                    if (query.Any())
                    {
                        foreach (var i in query)
                        {
                            ret.Add(string.Format("[{0}]{1}",i.id,i.name));
                        }
                           
                    }
                    return ret ;
                }
            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetProvider:" + ex.Message);
                return null;
            }

        }


        [OperationContract]
        public List<VW_PSS_DeviceInfo> GetDevice(short ProviderID, string Name, int Start, int Length)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from q in context.VW_PSS_DeviceInfo
                                where q.Device_Name.Contains(Name)
                                where q.Provider_ID == ProviderID
                                orderby q.Order_Total descending
                                select q;
                    if (query.Any())
                    {
                        return query.Skip(Start).Take(Length).ToList();
                    }
                    return new List<VW_PSS_DeviceInfo>();
                }
            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetDevice:" + ex.Message);
                return null;
            }
        }

        [OperationContract]
        public int SubmitOrder(PSS_Order_List OrderList, List<VW_OrderedDevice> vwList, short ProviderID,bool IsOrder)
        {
            try
            {
                this.Authoricate();

                System.Data.Common.DbTransaction tran = null;
                try
                {
                    lock (this)
                    {
                        using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                        {
                            context.Connection.Open();
                            tran = context.Connection.BeginTransaction();
                            context.Transaction = tran;

                            //1.写入PSS_Order_List

                            OrderList.Create_Time = DateTime.Now;
                            OrderList.PSS_Order_Type = (from a in context.PSS_Order_Type where a.Type_ID == (IsOrder ? 1:-1) select a).Single();
                            OrderList.PSS_Order_Status =
                                (from q in context.PSS_Order_Status
                                 where q.Status_ID == OrderList.PSS_Order_Type.Fisrt_Status_ID
                                 select q).Single();
                            OrderList.PSS_Provider = (from q in context.PSS_Provider
                                                      where q.Provider_ID == ProviderID
                                                      select q).Single();

                            context.PSS_Order_List.InsertOnSubmit(OrderList);

                            //2.写入PSS_Order_Device_List
                            List<PSS_Order_Device_List> pssOrderDeviceList = new List<PSS_Order_Device_List>(vwList.Count);

                            foreach (VW_OrderedDevice list in vwList)
                            {
                                PSS_Order_Device_List tem = new PSS_Order_Device_List();
                                tem.PSS_Order_List = OrderList;
                                var query = from q in context.PSS_Device_Info
                                            where q.Device_ID == list.Device_ID
                                            select q;
                                tem.PSS_Device_Info = query.Single();
                                tem.PSS_Device_Info.Order_Total += list.Total;

                                tem.Price = list.Price;
                                tem.Remark = list.Remark;
                                tem.Total = list.Total;
                                tem.Fee_Pack = list.Fee_Pack;
                                pssOrderDeviceList.Add(tem);


                            }
                            context.PSS_Order_Device_List.InsertAllOnSubmit(pssOrderDeviceList);

                            //3.生成下一步处理人记录
                            PSS_Order_Step nextStep = new PSS_Order_Step
                            {
                                PSS_Order_List = OrderList,
                                Last_Step_ID = -1,
                                OP_ID = OrderList.Create_ID, // OrderList.PSS_Order_Status.PSS_Status_OP_Users.OrderBy(p => p.Priority).First().OP_User_ID,
                                Receive_Time = DateTime.Now
                            };

                            context.PSS_Order_Step.InsertOnSubmit(nextStep);
                            context.SubmitChanges();
                            context.Transaction.Commit();

                            int email = this.DoMyWork(nextStep.Step_ID, OrderList.Subject, string.Empty, OrderDuration.Next);
                            if (email != 0 && email != 101 && email != 102)
                            {
                                context.PSS_Order_Step.DeleteOnSubmit(nextStep);
                                context.PSS_Order_Device_List.DeleteAllOnSubmit(pssOrderDeviceList);
                                context.PSS_Order_List.DeleteOnSubmit(OrderList);
                                context.SubmitChanges();
                            }

                            return email;
                        }
                    }
                }
                catch (Exception x)
                {
                    try
                    {
                        tran.Rollback();
                    }
                    catch
                    {
                        LogManager.Write("PSSService.SubmitOrder写入数据失败，事务回滚失败:" + x.Message);
                        return -2;
                    }
                    LogManager.Write("PSSService.SubmitOrder写入数据失败，事务回滚成功:" + x.Message);

                    return -1;
                }
            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.SubmitOrder:" + ex.Message);
                return -1;
            }
        }

        #endregion

        #region 订单查询

        [OperationContract]
        public List<VW_PSSOrderList> GetPSSOrderList(short ProviderID, string CreateID,
            string Subject, DateTime StartTime, DateTime EndTime, int Start, int Length)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from q in context.VW_PSSOrderList
                                where ProviderID == -1 || q.Provider_ID == ProviderID
                                where string.IsNullOrEmpty(CreateID) || q.Create_ID == CreateID
                                where q.Subject.Contains(Subject)
                                where q.Create_Time >= StartTime
                                where q.Create_Time <= EndTime
                                orderby q.Create_ID
                                select q;
                    if (query.Any())
                    {
                        return query.Skip(Start).Take(Length).ToList();
                    }
                    return new List<VW_PSSOrderList>();
                }
            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetPSSOrderList:" + ex.Message);
                return null;
            }
        }

        [OperationContract]
        public List<VW_PSSOrderStep> GetOrderStepByID(int OrderID)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from q in context.VW_PSSOrderStep
                                where q.Order_ID == OrderID
                                orderby q.Receive_Time
                                select q;
                    if (query.Any())
                    {
                        return query.ToList();
                    }
                    return new List<VW_PSSOrderStep>();
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetOrderStepByID:" + ex.Message);
                return null;
            }
        }


        [OperationContract]
        public string GetOrderBodyD(int OrderID)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from q in context.PSS_Order_List
                                where q.Order_ID == OrderID
                                select q.Body;
                    if (query.Any())
                    {
                        return query.Single();
                    }
                    return string.Empty;
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetOrderBodyD:" + ex.Message);
                return null;
            }
        }


        [OperationContract]
        public List<VW_PSSOrderDeviceDetail> GetOrderDeviceDetail(int OrderID)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from q in context.VW_PSSOrderDeviceDetail
                                where q.Order_ID == OrderID
                                select q;
                    if (query.Any())
                    {
                        return query.ToList();
                    }
                    return new List<VW_PSSOrderDeviceDetail>();
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetOrderDeviceDetail:" + ex.Message);
                return null;
            }
        }

        [OperationContract]
        public VW_PSSOrderUserDetail GetOrderUserDetail(int OrderID)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from q in context.VW_PSSOrderUserDetail
                                where q.Order_ID == OrderID
                                select q;
                    if (query.Any())
                    {
                        return query.Single();
                    }
                    return null;
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetOrderUserDetail:" + ex.Message);
                return null;
            }
        }
        #endregion

        #region 处理订单

        [OperationContract]
        public int DoMyWork(int StepID, string Body, string RcvUserID, OrderDuration Duration)
        {
            try
            {
                this.Authoricate();
                lock (this)
                {
                    using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                    {

                        PSS_Order_Step cur_step = (from q in context.PSS_Order_Step
                                               where q.Step_ID == StepID
                                               select q).Single();
                        if (cur_step.Completed_Time != null)
                        {
                            return 7;//当前步骤已经处理过了，不能再处理
                        }
                        cur_step.Body = Body;

                        cur_step.Completed_Time = DateTime.Now;

                        PSS_Order_List order = cur_step.PSS_Order_List;

                        if (order.Status_ID == (short)0)
                        {
                            return 6;//订单已经完成，不能再处理
                        }

                        PSS_Order_Step nextStep = new PSS_Order_Step()
                           {
                               Last_Step_ID = StepID,
                               Receive_Time = DateTime.Now
                           };

                        if (Duration == OrderDuration.Next)
                        {
                            if (order.Status_ID == 5)
                            {
                                //当前状态为发货
                                int ret = context.SP_PSS_Verify_IMEI_Ready(order.Order_ID);
                                if (ret != 0)
                                {
                                    return 10;
                                }

                            }

                            //下一步状态
                            order.PSS_Order_Status = (from q in context.PSS_Order_Status
                                                      where q.Status_ID == order.PSS_Order_Status.Next_Status_ID
                                                      select q).Single();
                            if (order.PSS_Order_Status.Status_ID == ((short)0))
                            {
                                //下一步是完成
                                order.Completed_Time = cur_step.Completed_Time;
                                context.SubmitChanges();
                                return 0;
                            }

                            nextStep.PSS_Order_List = order;
                            nextStep.OP_ID = order.PSS_Order_Status.PSS_Status_OP_Users.OrderBy(p => p.Priority).First().OP_User_ID;
                            if (nextStep.OP_ID.TrimEnd() == "-1")
                            {//返回到订单创建人
                                nextStep.OP_ID = order.Create_ID;
                            }
                            else if (nextStep.OP_ID.TrimEnd() == "-2")
                            {//转到对应的供货商
                                nextStep.OP_ID = order.PSS_Provider.User_ID;
                            }
                            context.PSS_Order_Step.InsertOnSubmit(nextStep);
                            context.SubmitChanges();
                        }
                        else if (Duration == OrderDuration.Rollback)
                        {
                            nextStep.PSS_Order_List = order;
                            var sts = from q in context.PSS_Order_Status
                                      where q.Next_Status_ID == order.PSS_Order_Status.Status_ID
                                      select q;
                            if (!sts.Any())
                            {
                                return 1;//开始步骤不允许回退。
                            }

                            order.PSS_Order_Status = sts.Single();

                            nextStep.OP_ID = (from q in context.PSS_Order_Step
                                              where q.Step_ID == cur_step.Last_Step_ID
                                              select q).Single().OP_ID;
                            if (nextStep.OP_ID.TrimEnd() == "-1")
                            {//返回到订单创建人
                                nextStep.OP_ID = order.Create_ID;
                            }
                            else if (nextStep.OP_ID.TrimEnd() == "-2")
                            {//转到对应的供货商
                                nextStep.OP_ID = order.PSS_Provider.User_ID;
                            }

                            context.PSS_Order_Step.InsertOnSubmit(nextStep);
                            context.SubmitChanges();
                        }
                        else if (Duration == OrderDuration.Send)
                        {
                            nextStep.PSS_Order_List = order;

                            if (cur_step.OP_ID == RcvUserID) return 2;//不允许转派给自己

                            nextStep.OP_ID = RcvUserID;


                            context.PSS_Order_Step.InsertOnSubmit(nextStep);
                            context.SubmitChanges();
                        }
                        else if (Duration == OrderDuration.Deny)
                        {
                            //否决订单
                            if (order.Status_ID == 1 || order.Status_ID == 5 || order.Status_ID == 12)                             
                            {//订货、发货、退货审批 可以否决
                                //var queryAu = from q in order.PSS_Order_Status.PSS_Status_OP_Users
                                //              where q.OP_User_ID == cur_step.OP_ID
                                //              select q;
                                if (order.Status_ID !=1 && order.Status_ID!=11)
                                {
                                    return 5;//无权否绝审批。
                                }

                                order.PSS_Order_Status = (from q in context.PSS_Order_Status
                                                          where q.Status_ID == 999
                                                          select q).Single();

                                order.Completed_Time = DateTime.Now;
                                context.SubmitChanges();
                                using (DataClassesQueryDataContext userContext = new DataClassesQueryDataContext())
                                {
                                    var query = (from q in userContext.UserInfor
                                                 where q.User_ID == order.Create_ID
                                                 select q).Single();
                                    try
                                    {
                                        this.SendEmail("渠道综合支撑系统提示", "渠道综合支撑系统提示:您有一个供销订单被否绝，请登录系统查看。", query.Email);
                                        return 0;
                                    }
                                    catch (Exception ex)
                                    {
                                        LogManager.Write("PSSService.Email: " + ex.Message);
                                        return 102;//发送提醒邮件失败
                                    }
                                }
                            }
                            else
                            {
                                return 4;//此状态的订单不允许否绝
                            }
                        }
                        else
                        {
                            return 3;//未知的工单流向
                        }


                        //4.发送Email
                        using (DataClassesQueryDataContext userContext = new DataClassesQueryDataContext())
                        {
                            // UserInfor Sender = userContext.UserInfor.Select((p => p.User_ID = OrderList.Create_ID);
                            //         string 
                            var query = from q in userContext.UserInfor
                                        where q.User_ID == cur_step.OP_ID || q.User_ID == nextStep.OP_ID
                                        select q;
                            var cUser = from c in query
                                        where c.User_ID == cur_step.OP_ID
                                        select c.UserName;
                            var nEmail = from n in query
                                         where n.User_ID == nextStep.OP_ID
                                         select n.Email;
                            if (!cUser.Any() || !nEmail.Any())
                            {
                                LogManager.Write("PSSService.Email: 查询用户信息异常");
                                return 101;//查询邮件用户信息异常
                            }
                            string Msg = string.Format("您好！您在渠道综合支撑系统有新的待办事宜({0}发):{1}。请尽快处理。",
                                    cUser.First(), order.Subject);
                            try
                            {
                                this.SendEmail(string.Format("渠道综合支撑系统提示:您有新待办事宜({0}发):{1}",
                                                             cUser.First(), order.Subject), Msg, nEmail.First());
                            }
                            catch (Exception ex)
                            {
                                LogManager.Write("PSSService.Email: " + ex.Message);
                                return 102;//发送提醒邮件失败
                            }

                        }

                    }
                    return 0;
                }
            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.DoMyWork:" + ex.Message);
                return -1;//未知错误
            }
        }


        [OperationContract]
        public List<VW_PSSMyOrderList> GetMyWork(string UserID)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from q in context.VW_PSSMyOrderList
                                where q.OP_ID == UserID
                                orderby q.Create_Time
                                select q;
                    if (query.Any())
                    {
                        return query.ToList();
                    }
                    return new List<VW_PSSMyOrderList>();
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetMyWork:" + ex.Message);
                return null;
            }
        }

        [OperationContract]
        public List<string> GetAbleSendUsers(int StepID, string CurUserID)
        {
            try
            {
                this.Authoricate();
                List<string> list = new List<string>();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from q in context.PSS_Order_Step
                                where q.Step_ID == StepID
                                select q;
                    if (query.Any())
                    {
                        var users = query.Single().PSS_Order_List.PSS_Order_Status.PSS_Status_OP_Users;
                        var idlist = (from u in users where u.OP_User_ID != CurUserID select u.OP_User_ID).ToList();
                        using (DataClassesQueryDataContext usercontext = new DataClassesQueryDataContext())
                        {
                            var qq = from q in usercontext.UserInfor
                                     where idlist.Contains(q.User_ID)
                                     select new { id = q.User_ID, name = q.UserName };
                            if (qq.Any())
                            {
                                foreach (var i in qq)
                                {
                                    list.Add(string.Format("[{0}]{1}", i.id, i.name));
                                }
                            }

                        }
                    }
                    return list;
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetAbleSendUsers:" + ex.Message);
                return null;
            }
        }

        #endregion

        #region 串号管理

        [OperationContract]
        public List<VW_PSSOrderIMEI> GetIMEIByOrderID(int OrderID)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from q in context.VW_PSSOrderIMEI
                                where q.Order_ID == OrderID
                                orderby q.Device_ID
                                select q;
                    if (query.Any())
                    {
                        return query.ToList();
                    }
                    return new List<VW_PSSOrderIMEI>();
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetIMEIByOrderID:" + ex.Message);
                return null;
            }
        }

        [OperationContract]
        public string InsertIMEI(List<VW_PSSOrderIMEI> IMEIList, string UserID)
        {
            try
            {
                this.Authoricate();
                lock (this)
                {
                    using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                    {

                        //1.检查总数是否一致
                        var query = from q in context.VW_PSSOrderIMEI
                                    where q.Order_ID == IMEIList[0].Order_ID
                                    orderby q.Device_ID
                                    select q;
                        if (query.Any())
                        {
                            List<VW_PSSOrderIMEI> temlist = query.ToList();
                            temlist.AddRange(IMEIList);

                            //检查总数是否一致
                            var deviceList = from q in context.PSS_Order_Device_List
                                             where q.Order_ID == temlist[0].Order_ID
                                             select new
                                             {
                                                 id = q.Device_ID,
                                                 count = q.Total
                                             };

                            foreach (var d in deviceList)
                            {
                                if (temlist.Count(p => p.Device_ID == d.id) > d.count)
                                {
                                    return string.Format("终端[{0}]的串号数量与预订数量不一致", d.id);
                                }
                            }
                        }
                        //2.检查串号是否重复
                        var iquery = from q in context.PSS_Order_Device_IMEI
                                     join o in context.PSS_Order_List on q.Order_ID equals o.Order_ID
                                     where o.Type_ID == -1
                                     where IMEIList.Select(p => p.IMEI).Contains(q.IMEI)
                                     select q.IMEI;
                        if (iquery.Any())
                        {
                            string result = string.Empty;
                            foreach (string s in iquery.Distinct())
                            {
                                result += (s + "\r\n");
                            }
                            return "以下串号与系统已有串号重复，请核实:\r\n" + result;
                        }

                        //3.导入 
                        List<PSS_Order_Device_IMEI> pssImei = new List<PSS_Order_Device_IMEI>();
                        PSS_Order_List order = (from q in context.PSS_Order_List
                                                where q.Order_ID == IMEIList[0].Order_ID
                                                select q).Single();
                        foreach (VW_PSSOrderIMEI i in IMEIList)
                        {
                            pssImei.Add(new PSS_Order_Device_IMEI
                            {
                                Create_ID = UserID,
                                Create_Time = DateTime.Now,
                                Device_ID = i.Device_ID,
                                IMEI = i.IMEI,
                                PSS_Order_List = order
                            });
                        }

                        context.PSS_Order_Device_IMEI.InsertAllOnSubmit(pssImei);
                        context.SubmitChanges();
                        return string.Empty;
                    }
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.InsertIMEI:" + ex.Message);
                return "未知错误";
            }
        }

        [OperationContract]
        public bool DeleteIMEI(int OrderID, string IMEI)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var order = from o in context.PSS_Order_List
                                where o.Order_ID == OrderID
                                select o;
                    if (order.Single().Status_ID != 5
                        && order.Single().Status_ID != 13)
                    {
                        //非发货状态不能删除串号
                        return false;
                    }

                    var query = from q in context.PSS_Order_Device_IMEI
                                where q.Order_ID == OrderID
                                where q.IMEI == IMEI
                                select q;
                    if (query.Any())
                    {
                        
                        context.PSS_Order_Device_IMEI.DeleteAllOnSubmit(query);
                        context.SubmitChanges();

                    }

                    return true;
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("PSSService.DeleteIMEI:" + ex.Message);
                return false;
            }
        }

        #endregion

        #region 退货管理

        //[OperationContract]
        //public UnpurchaseIMEI GetIMEIInfo(string IMEI,string ChannelID)
        //{
        //    try
        //    {
        //        this.Authoricate();
        //        using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
        //        {
        //            UnpurchaseIMEI imei = new UnpurchaseIMEI();
        //            var query = from a in context.PSS_Order_Device_IMEI
        //                        join b in context.PSS_Device_Info on a.Device_ID equals b.Device_ID
        //                        join c in context.PSS_Order_List on a.Order_ID equals c.Order_ID
        //                        where c.Type_ID == 1
        //                        where c.Status_ID==0
        //                        where a.IMEI==IMEI
        //                        where c.Channel_ID== ChannelID
        //                        select new
        //                        {
        //                            imei = a.IMEI,
        //                            providerID = b.Provider_ID,
        //                            deviceID = a.Device_ID,
        //                            deviceName = b.Device_Name,
        //                            time = c.Create_Time,
        //                            price = b.Price * 0.01
        //                        };
        //            if (query.Count() != 1)
        //            {
        //                //没有预订记录
        //                return  new UnpurchaseIMEI{ IMEI="-1"};
        //            }
                    

        //            var tem = query.Single();


        //            var temquery = from a in context.PSS_Order_Device_IMEI
        //                           join b in context.PSS_Order_List on a.Order_ID equals b.Order_ID
        //                           where b.Type_ID == -1
        //                           where a.IMEI == tem.imei
        //                           select a.IMEI;

        //            if (temquery.Any())
        //            {
        //                //已经是退货状态
        //                return new UnpurchaseIMEI { IMEI = "-2" };
        //            }

        //            imei.IMEI = tem.imei;
        //            imei.DeviceID = tem.deviceID;
        //            imei.DeviceName = tem.deviceName;
        //            imei.OrderTime = tem.time;
        //            imei.Price = (decimal)tem.price;
        //            imei.ProviderID = tem.providerID;
        //            return imei;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        LogManager.Write("PSSService.GetIMEIInfo:" + ex.Message);
        //        return null;
        //    }
        //}

        [OperationContract]
        public string SubmitUnpurchase(PSS_Order_List Order, List<UnpurchaseIMEI> IMEIList)
        {

            try
            {
                var tem = from a in IMEIList
                          group a.IMEI by a.DeviceID
                              into deviceTotal
                              select new { id = deviceTotal.Key, count = deviceTotal.Count() };

                List<VW_OrderedDevice> vList = new List<VW_OrderedDevice>(tem.Count());
                foreach (var e in tem)
                {
                    vList.Add(new VW_OrderedDevice
                    {
                        Device_ID = e.id,
                        Price = (int)((from q in IMEIList
                                       where q.DeviceID == e.id
                                       select q.Price).First() * 100),
                        Total = e.count,
                        Fee_Pack = (short)0,
                        Remark = string.Empty
                    });
                }

                int ret = this.SubmitOrder(Order, vList, IMEIList[0].ProviderID, false);
                if (ret == 0 || ret == 101 || ret == 102)
                {
                    List<VW_PSSOrderIMEI> iList = new List<VW_PSSOrderIMEI>(IMEIList.Count);

                    foreach (UnpurchaseIMEI i in IMEIList)
                    {
                        iList.Add(new VW_PSSOrderIMEI
                        {
                            Device_ID = i.DeviceID,
                            IMEI = i.IMEI,
                            Order_ID = Order.Order_ID
                        });
                    }


                    return this.InsertIMEI(iList, Order.Create_ID);
                }
                else
                {
                    return "生成退货主订单失败";
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("PSSService.SubmitUnpurchase:" + ex.Message);
                return "未知错误";
            }

        }

        [OperationContract]
        public string GetProviderDetail(int StepID)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from a in context.PSS_Order_Step
                                where a.Step_ID == StepID
                                where a.Completed_Time ==null
                                select a;
                    if (!query.Any())
                    {
                        return "-1";
                    }
                    PSS_Order_List Order = query.Single().PSS_Order_List;

                    if (Order.Status_ID != 13
                        || Order.Type_ID != -1)
                    {
                        return "-2";//当前订单不是退货发货状态
                    }

                    PSS_Provider pro = Order.PSS_Provider;
                    string msg = string.Empty;

                    msg = string.Format("供应商编号：{0}\r\n供应商名称：{1}\r\n负责人：{2}\r\n联系电话：{3}\r\n地址：{4}邮编：{5}",
                        pro.Provider_ID, pro.Provider_Name, pro.Person_In_Charge, pro.Tel, pro.Address, pro.Postcode);
                    return msg;
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("PSSService.GetProvider:" + ex.Message);
                return "-3";
            }
        }
        #endregion

        #region  供应商维护
        [OperationContract]
        public List<PSS_Provider> GetProvderByName(string Name)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    //由于PSSPP_Provider是主健表，直接序列化会把其所有关联表都包括其中，无法完成
                    //设置ObjectTrackingEnabled=false则关于关联表序列化
                    context.ObjectTrackingEnabled = false;
                    var query = from q in context.PSS_Provider
                                where q.Provider_Name.Contains(Name) || string.IsNullOrEmpty(Name)
                                select q;
                    if (query.Any())
                    {
                        return query.ToList();
                    }
                    return new List<PSS_Provider>();
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetProvderByName:" + ex.Message);
                return null;
            }
        }
        [OperationContract]
        public int CreateProvider(PSS_Provider provider)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    context.PSS_Provider.InsertOnSubmit(provider);
                    context.SubmitChanges();
                   
                }
                return 0;
            }
            catch (Exception ex)
            {
                if(ex.Message.Contains("ind_pss_provider_user"))
                {
                    return 1;//供应商已存在
                }

                LogManager.Write("PSSService.CreateProvider:" + ex.Message);
                return -1;
            }
        }

        [OperationContract]
        public int UpdateProvider(PSS_Provider provider)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from q in context.PSS_Provider
                                where q.Provider_ID == provider.Provider_ID
                                select q;
                    if (query.Any())
                    {
                        PSS_Provider first = query.Single();
                        first.Provider_Name = provider.Provider_Name;
                        first.Is_Enable = provider.Is_Enable;
                        first.Person_In_Charge = provider.Person_In_Charge;
                        first.User_ID = provider.User_ID;
                        first.Tel = provider.Tel;
                        first.Bank = provider.Bank;
                        first.Bank_Account_Name = provider.Bank_Account_Name;
                        first.Bank_Account = provider.Bank_Account;
                        first.Postcode = provider.Postcode;
                        first.Address = provider.Address;
                        first.Update_ID = provider.Update_ID;
                        first.Update_Time = DateTime.Now;
                        first.Remark = provider.Remark;
                        //context.PSS_Provider_His.InsertOnSubmit(
                        //    new PSS_Provider_His
                        //    {
                        //        Provider_ID= first.Provider_ID,
                        //        Provider_Name = first.Provider_Name,
                        //        Is_Enable = first.Is_Enable,
                        //        Person_In_Charge = first.Person_In_Charge,
                        //        User_ID = first.User_ID,
                        //        Tel = first.Tel,
                        //        Bank = first.Bank,
                        //        Bank_Account_Name = first.Bank_Account_Name,
                        //        Bank_Account = first.Bank_Account,
                        //        Postcode = first.Postcode,
                        //        Address = first.Address,
                        //        Create_ID = first.Create_ID,
                        //        Create_Time = first.Create_Time,
                        //        Update_ID = first.Update_ID,
                        //        Update_Time = first.Update_Time,
                        //        Remark = first.Remark

                        //    });

                        context.SubmitChanges();
                        return 0;
                    }
                    return 1;
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("ind_pss_provider_user"))
                {
                    return 2;//供应商已存在
                }

                LogManager.Write("PSSService.UpdateProvider:" + ex.Message);
                return -1;
            }
        }

        [OperationContract]
        public List<PSS_Provider_His> GetProviderHis(string Name)
        {

            try
            {
                this.Authoricate();
                List<PSS_Provider_His> list = new List<PSS_Provider_His>();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from q in context.PSS_Provider_His
                                where q.Provider_Name.Contains(Name) || string.IsNullOrEmpty(Name)
                                select q;
                    if (query.Any())
                    {
                        list.AddRange(query);
                        //foreach (PSS_Provider_His first in query)
                        //{
                        //    list.Add(new PSS_Provider
                        //    {
                        //        Provider_ID = first.Provider_ID,
                        //        Provider_Name = first.Provider_Name,
                        //        Is_Enable = first.Is_Enable,
                        //        Person_In_Charge = first.Person_In_Charge,
                        //        User_ID = first.User_ID,
                        //        Tel = first.Tel,
                        //        Bank = first.Bank,
                        //        Bank_Account_Name = first.Bank_Account_Name,
                        //        Bank_Account = first.Bank_Account,
                        //        Postcode = first.Postcode,
                        //        Address = first.Address,
                        //        Create_ID = first.Create_ID,
                        //        Create_Time = first.Create_Time,
                        //        Update_ID = first.Update_ID,
                        //        Update_Time = first.Update_Time,
                        //        Remark = first.Remark
                        //    });
                        //}
                        var newPro = from a in context.PSS_Provider
                                     where list.Select(p=>p.Provider_ID).Contains(a.Provider_ID)
                                     select a;
                        //list.AddRange(newPro);
                        foreach (var first in newPro)
                        {
                            list.Add(new PSS_Provider_His
                            {
                                Provider_ID = first.Provider_ID,
                                Provider_Name = first.Provider_Name,
                                Is_Enable = first.Is_Enable,
                                Person_In_Charge = first.Person_In_Charge,
                                User_ID = first.User_ID,
                                Tel = first.Tel,
                                Bank = first.Bank,
                                Bank_Account_Name = first.Bank_Account_Name,
                                Bank_Account = first.Bank_Account,
                                Postcode = first.Postcode,
                                Address = first.Address,
                                Create_ID = first.Create_ID,
                                Create_Time = first.Create_Time,
                                Update_ID = first.Update_ID,
                                Update_Time = first.Update_Time,
                                Remark = first.Remark
                            });
                        }
                        var c =from a in list                                
                                orderby a.Provider_ID
                                orderby a.Update_Time descending
                                select a;
                        return c.ToList();
                    }
                    return new List<PSS_Provider_His>();
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetProviderHis:" + ex.Message);
                return null;
            }
        }
        #endregion


        #region  终端维护
        [OperationContract]
        public PSS_Device_Info GetDeviceDetailByID(int ID)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    //由于PSSPP_Provider是主健表，直接序列化会把其所有关联表都包括其中，无法完成
                    //设置ObjectTrackingEnabled=false则关于关联表序列化
                    context.ObjectTrackingEnabled = false;
                    var query = from q in context.PSS_Device_Info
                                where q.Device_ID== ID
                                select q;
                    if (query.Any())
                    {
                        return query.First();
                    }
                    return new PSS_Device_Info();
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetDeviceDetailByID:" + ex.Message);
                return null;
            }
        }

        [OperationContract]
        public string CreateDevice(List<PSS_Device_Info> newList)
        {
            try
            {
                this.Authoricate();
                lock (this)
                {
                    using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                    {
                        List<string> nameList = new List<string>(newList.Count);
                        foreach (var a in newList)
                        {
                            nameList.Add(a.Device_Name);
                        }
                        var nameQuery = from q in context.PSS_Device_Info
                                        where nameList.Contains(q.Device_Name)
                                        select new { q.Device_Name };
                        if (nameQuery.Any())
                        {
                            string i = string.Empty;
                            foreach (var s in nameQuery)
                            {
                                i += (s + ";");
                            }
                            return "重复入库：" + i; //
                        }
                        DateTime now = DateTime.Now;
                        foreach (var a in newList)
                        {
                            a.Create_Time = now;
                            a.Update_Time = null;
                        }
                        context.PSS_Device_Info.InsertAllOnSubmit(newList);
                        context.SubmitChanges();

                    } 
                }
                return string.Empty;

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.CreateDevice:" + ex.Message);
                return ex.Message;
            }
        }

        [OperationContract]
        public string UpdateDevice(PSS_Device_Info newDevice)
        {
            try
            {
                this.Authoricate();
                lock (this)
                {
                    using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                    {
                        var query = from q in context.PSS_Device_Info
                                    where q.Device_ID == newDevice.Device_ID
                                    select q;
                        if (query.Any())
                        {
                            PSS_Device_Info first = query.First();

                            first.Device_Name = newDevice.Device_Name;
                            first.Is_Enable = newDevice.Is_Enable;
                            first.Fac_Name = newDevice.Fac_Name;
                            first.Price = newDevice.Price;
                            first.Picture_Path = newDevice.Picture_Path;
                            first.Order_Total = newDevice.Order_Total;
                            first.G3_Flag = newDevice.G3_Flag;
                            first.Smart_Flag = newDevice.Smart_Flag;
                            first.Baojia_Flag = newDevice.Baojia_Flag;
                            first.Baojia_Duration = newDevice.Baojia_Duration;
                            first.Return_Value = newDevice.Return_Value;
                            first.Stock_Price = newDevice.Stock_Price;
                            first.Stock = newDevice.Stock;
                            first.BOSS_Fac_ID = newDevice.BOSS_Fac_ID;
                            first.BOSS_Device_ID = newDevice.BOSS_Device_ID;
                            first.Create_Time = newDevice.Create_Time;
                            first.Create_ID = newDevice.Create_ID;
                            first.Update_Time = newDevice.Update_Time;
                            first.Update_ID = newDevice.Update_ID;
                            first.Remark = newDevice.Remark;


                            context.SubmitChanges();
                            return string.Empty;
                        }
                        return "终端不存在或已删除，无法更新";

                    }
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.UpdateDevice:" + ex.Message);
                return ex.Message;
            }
        }

        [OperationContract]
        public string DelDevice(int ID)
        {
            try
            {
                this.Authoricate();
                lock (this)
                {
                    using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                    {
                        var query = from q in context.PSS_Device_Info
                                    where q.Device_ID == ID
                                    select q;
                        if (query.Any())
                        {
                            query.First().Is_Enable = '0';
                            
                            context.SubmitChanges();
                            return string.Empty;
                        }
                        return "终端不存在或已删除，无法删除";

                    }
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.DelDevice:" + ex.Message);
                return ex.Message;
            }
        }

        #endregion

        #region 报表

        [OperationContract]
        public List<string> GetAllPSSReport()
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    DateTime now = DateTime.Now;
                    var query = from q in context.PSS_Report
                                where q.Create_Time<= now
                                where q.Status=='1'
                                orderby q.ID
                                select q;
                    
                    if (query.Any())
                    {
                        List<string> ret = new List<string>(query.Count());
                        foreach (var a in query)
                        {
                            ret.Add(string.Format("[{0}]{1}",a.ID,a.Name));
                        }
                        return ret;
                    }
                    return new List<string>();
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetAllPSSReport:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="Start"></param>
        /// <param name="End"></param>
        /// <param name="ProviderID">为-1时，统计所有供应商订单，否则统计指定供应商订单</param>
        /// <param name="ChannelID">为-1时，统计所有渠道，否则统计指定渠道</param>
        /// <returns></returns>
        DataTable GetReportTable(int ID, string Start, string End, int ProviderID, string ChannelID,int RowCount,string UserID)
        {
            string query = string.Empty;
            using (StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(string.Format(@"./Script/PSS_{0}.sql",ID)),Encoding.Default))
            {
                query = reader.ReadToEnd();
               
            }
            query = string.Format(query, Start, End, ProviderID, ChannelID, RowCount>0? RowCount:999999999,UserID);
            DataTable table = new DataTable();
            table.TableName = "PSS_Report_" + ID.ToString();

            using (SqlConnection con = new SqlConnection(SqlString))
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandTimeout = 600;
                cmd.Connection = con;
                cmd.CommandText = query;

                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                sda.Fill(table);
            }

            return table;
        }

        /// <summary>
        /// 直接返回表格，前100行
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="Start"></param>
        /// <param name="End"></param>
        /// <param name="ProviderID"></param>
        /// <param name="ChannelID"></param>
        /// <returns></returns>
        [OperationContract]
        public XDataTable GetReportByTable(int ID, string Start, string End, int ProviderID, string ChannelID,string UserID)
        {
            try
            {
                this.Authoricate();

                return new XDataTable(GetReportTable(ID, Start, End, ProviderID, ChannelID, 100, UserID));
            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetReportByTable:" + ex.Message);
                return null;
            }
        }

        [OperationContract]
        public string GetReportByFile(int ID, string Start, string End, int ProviderID, string ChannelID,string UserID)
        {
            try
            {
                this.Authoricate();

                DataTable table = GetReportTable(ID, Start, End, ProviderID, ChannelID, -1, UserID);
                table.TableName = "Pss_Report_" + ID.ToString();
                string filename = WriteTableIntoFile(table, table.TableName);
                return filename;
            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GetReportByFile:" + ex.Message);
                return null;
            }
        }

        #endregion

        #region 供应商自销管理

        [OperationContract]
        public string Self_AddStorage(List<PSS_Self_Storage> NewStorageList)
        {
            try
            {
                this.Authoricate();
                lock (this)
                {
                    using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                    {
                        List<string> ilist = new List<string>(NewStorageList.Count);

                        foreach (var i in NewStorageList)
                        {
                            ilist.Add(i.IMEI1);
                            ilist.Add(i.IMEI2);
                            ilist.Add(i.IMEI3);
                        }
                        var query = from a in context.PSS_Self_Storage
                            where ilist.Contains(a.IMEI1) || ilist.Contains(a.IMEI2) || ilist.Contains(a.IMEI3)
                            select new {a.IMEI1, a.IMEI2, a.IMEI3};
                        if (query.Any())
                        {
                            var dbList = query.ToList().Select(a=> new string[] {a.IMEI1, a.IMEI2, a.IMEI3}) .SelectMany(x=>x).ToList();
                            var reEtnerList = ilist.Where(x => dbList.Any(y => y == x)).ToArray();
                     
                            return "重复入库：" + string.Join(";", reEtnerList); 
                        }
                        string nbr = Guid.NewGuid().ToString("N");
                        DateTime now = DateTime.Now;
                        foreach (var a in NewStorageList)
                        {
                            a.Storage_NBR = nbr;
                            a.Store_Time = now;
                        }
                        context.PSS_Self_Storage.InsertAllOnSubmit(NewStorageList);
                        context.SubmitChanges();
                        return string.Empty;
                    } 
                }
            
            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.Self_AddStorage:" + ex.Message);
                return "未知错误";
            }
        }

        [OperationContract]
        public List<string> Self_GetDeviceListByPID(bool IsWithUnable)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from a in context.PSS_Device_Info
                                where IsWithUnable ||( !IsWithUnable && a.Is_Enable == '1')
                                select new { a.Device_ID, a.Device_Name };
                    List<string> ret = new List<string>(query.Count());
                    foreach (var a in query)
                    {
                        ret.Add(string.Format("[{0}]{1}", a.Device_ID, a.Device_Name));
                    }
                    return ret;
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.Self_GetDeviceListByPID:" + ex.Message);
                return null;
            }
        }

        [OperationContract]
        public List<VW_PSS_Self_Storage> Self_GetDeviceStorageInfo(string IMEI)
        {
        try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var query = from a in context.VW_PSS_Self_Storage
                                where a.IMEI1 == IMEI || a.IMEI2 == IMEI || a.IMEI3 == IMEI
                                select a;
                    if (query.Any())
                    {
                        return query.ToList();
                    }
                    return new List<VW_PSS_Self_Storage>();
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.Self_GetDeviceStorageInfo:" + ex.Message);
                return null;
            }
        }

        [OperationContract]
        public PayResult Self_Pay(List<PSS_Self_Storage> list, string GroupUserPhone,
            string GroupID, string GroupName, string CustManagerID)
        {
            try
            {
                this.Authoricate();
                lock (this)
                {
                    using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                    {
                        List<string> ilist = new List<string>(list.Count);
                        foreach (var i in list)
                        {
                            ilist.Add(i.IMEI1);
                            ilist.Add(i.IMEI2);
                            ilist.Add(i.IMEI3);
                        }
                        var query = from a in context.PSS_Self_Storage
                                    where ilist.Contains(a.IMEI1) || ilist.Contains(a.IMEI2) || ilist.Contains(a.IMEI3)
                                    where a.Sale_Time != null
                                    select new { a.IMEI1, a.IMEI2, a.IMEI3 };
                        if (query.Any())
                        {
                            var dbList = query.ToList().Select(a => new string[] { a.IMEI1, a.IMEI2, a.IMEI3 }).SelectMany(x => x).ToList();
                            var reEtnerList = ilist.Where(x => dbList.Any(y => y == x)).ToArray();

                            return new PayResult {Message = "重复销售：" + string.Join(";", reEtnerList)};
                        }
                     
                        DateTime now = DateTime.Now;

                        foreach (var a in list)
                        {
                            var pay = from p in context.PSS_Self_Storage
                                      where p.IMEI1 == a.IMEI1 || p.IMEI2 == a.IMEI1 || a.IMEI3 == a.IMEI1
                                      select p;
                            PSS_Self_Storage pss = pay.First();
                            pss.Sale_Time = now;
                            pss.Sale_User_ID = a.Sale_User_ID;
                            pss.Sale_Price = a.Sale_Price;
                            pss.Pay_Method_ID = a.Pay_Method_ID;
                            pss.Serv_Number = a.Serv_Number;
                            pss.Guide = a.Guide;

                            PSS_Score score = new PSS_Score();
                            score.Serv_Number = a.Serv_Number;
                            score.Score = a.Sale_Price.Value / 100;
                            score.Sale_IMEI = a.IMEI1;
                            score.Create_ID = a.Sale_User_ID;
                            score.Create_Time = now;
                            score.Device_ID = a.Device_ID;
                            score.Provider_ID = pss.Provider_ID;
                            score.Create_Year = score.Create_Time.Year;
                            context.PSS_Score.InsertOnSubmit(score);

                            if (!string.IsNullOrEmpty(GroupUserPhone))
                            {
                                Group_Tehui th = new Group_Tehui();
                                th.Sale_ID = pss.ID;
                                th.Serv_Number = GroupUserPhone;
                                th.Group_ID = GroupID;
                                th.Group_Name = GroupName;
                                th.Cust_Manager_ID = CustManagerID;
                                context.Group_Tehui.InsertOnSubmit(th);
                            }
                        }
                       

                        context.SubmitChanges();
                        var squery = context.PSS_Score.Where(x=>x.Serv_Number==list[0].Serv_Number).Where(a=>a.Create_Year>=DateTime.Today.Year-1).Sum(s => s.Score);

                        return new PayResult { Message = string.Empty ,TotalScore =squery};
                    } 
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.Self_Pay:" + ex.Message);
                return new PayResult { Message = ex.Message };
            }
        }

        [OperationContract]
        public string Self_UnStore(string IMEI)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {

                    var query = from q in context.PSS_Self_Storage
                                where q.IMEI1 == IMEI || q.IMEI2 == IMEI || q.IMEI3 == IMEI
                                select q;

                    if (query.Any())
                    {
                        PSS_Self_Storage s = query.First();
                        if (s.Sale_Time == null)
                        {
                            
                            context.PSS_Self_Storage.DeleteOnSubmit(s);                           
                            context.SubmitChanges();
                            return string.Empty;
                        }
                        else
                        {
                            return "已销售的终端不能退库";
                        }
                    }
                    else
                    {
                        return "手机终端不存在";
                    }

                   
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.Self_UnStore:" + ex.Message);
                return "未知错误";
            }
        }


        [OperationContract]
        public List<VW_PSS_Bill> Self_Bill(int Bill_Day)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {

                    var query = from q in context.VW_PSS_Bill
                                where q.Sale_Day==Bill_Day
                                select q;

                    if (query.Any())
                    {
                        return query.ToList();
                    }
                    return new List<VW_PSS_Bill>();

                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.Self_Bill:" + ex.Message);
                return null;
            }
        }
        [OperationContract]
        public string  Self_UnSale(PSS_Self_UnSale unSale)
        {
            try
            {
                this.Authoricate();
                lock (this)
                {
                    using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                    {

                        var query = from q in context.PSS_Self_Storage
                                    where q.IMEI1 == unSale.IMEI || q.IMEI1 == unSale.IMEI || q.IMEI1 == unSale.IMEI
                                    select q;

                        if (query.Any())
                        {
                            PSS_Self_Storage sale = query.First();
                            if (sale.Sale_Time == null)
                            {
                                return "未销售的终端不能撤单";
                            }

                            var score = from a in context.PSS_Score
                                        where a.Sale_IMEI == unSale.IMEI
                                        select a;

                            if(score.Any())
                            {
                                PSS_Score sfirst = score.First();
                                if (context.PSS_Score.Where(a => a.Serv_Number == sfirst.Serv_Number).Where(b => b.Create_Time > sfirst.Create_Time).Where
                                    (c => c.Score < 0).Any())
                                {
                                    return "用户已兑换积分无法撤单";
                                }

                                context.PSS_Score.DeleteOnSubmit(sfirst);
                            }


                            sale.Sale_Time = null;
                            sale.Sale_Price = null;
                            sale.Sale_User_ID = null;
                            sale.Pay_Method_ID = null;
                            sale.Guide = null;

                            unSale.UnSale_Time = DateTime.Now;
                            context.PSS_Self_UnSale.InsertOnSubmit(unSale);
                            var th = context.Group_Tehui.Where(a => a.Sale_ID == sale.ID);
                            if (th.Any())
                            {
                                context.Group_Tehui.DeleteOnSubmit(th.First());
                            }
                            context.SubmitChanges();
                            return string.Empty; ;
                        }
                        return "终端未入库，无法撤单";

                    } 
                }

            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.Self_UnSale:" + ex.Message);
                return ex.Message;
            }
        }

        [OperationContract]
        public string GroupTHSendVerifyCode(string CustManagerID,string VerifyCode)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    var c = context.Cust_Manager.Where(a => a.Cust_Manager_ID == CustManagerID);
                    if (!c.Any())
                    {
                        return "-1";//客户经理不存在
                    }

                    if (this.SendEmailDirectly("集团特惠活动验证码：" + VerifyCode, "", c.First().Email))
                    {

                        return c.First().Cust_Manager_Name;
                    }

                    return "-2";//发送验证码失败;
                }
            }
            catch (Exception ex)
            {

                LogManager.Write("PSSService.GroupTHSendVerifyCode:" + ex.Message);
                return "-3";//未知错误

            }
        }

        #endregion

        #region 积分兑换
        [OperationContract]
        public List<VW_PSS_Score_His> GetScoreHis(string ServNumber)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext  context = new PSSDataClassesDataContext())
                {
                    var query = from a in context.VW_PSS_Score_His
                                where a.Serv_Number == ServNumber
                                orderby a.Create_Time
                                select a;
                    if (query.Any())
                    {
                        return query.ToList();
                    }
                    return new List<VW_PSS_Score_His>();
                }
            }
            catch (Exception e)
            {
                LogManager.Write("PSSService.GetScoreHis:" + e.Message);
                return null;
            }
        }

        [OperationContract]
        public List<PSS_Score_Gift> GetValidGift (string GiftName)
        {
            try
            {
                this.Authoricate();
                using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                {
                    context.ObjectTrackingEnabled = false;

                    var query = from a in context.PSS_Score_Gift
                                where a.Gift_Name.Contains(GiftName)
                                orderby a.Create_Time
                                select a;
                    if (query.Any())
                    {
                        return query.ToList();
                    }
                    return new List<PSS_Score_Gift>();
                }
            }
            catch (Exception e)
            {
                LogManager.Write("PSSService.GetValidGift:" + e.Message);
                return null;
            }
        }

        [OperationContract]
        public string  ExchangeScore(string ServNumber,int GiftID,string UserID)
        {
            try
            {
                lock (this)
                {
                    this.Authoricate();
                    using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                    {
                        int vscore = context.PSS_Score.Where(a => a.Serv_Number == ServNumber).Where
                            (y => y.Create_Year >= DateTime.Now.Year - 1).Sum(b => b.Score);
                        PSS_Score_Gift gift = context.PSS_Score_Gift.Where(a => a.ID == GiftID).First();

                        if (vscore < gift.Score)
                        {
                            return "用户当前可用积分【"+vscore.ToString()+"】不足";
                        }
                        PSS_Score newScore = new PSS_Score();

                        newScore.Serv_Number = ServNumber;
                        newScore.Score = gift.Score * (-1);
                        newScore.PSS_Score_Gift = gift;
                    
                        newScore.Create_ID = UserID;
                        newScore.Create_Time=DateTime.Now;
                        newScore.Create_Year = newScore.Create_Time.Year;

                        context.PSS_Score.InsertOnSubmit(newScore);
                        context.SubmitChanges();
                        return string.Empty;
                    } 
                }
            }
            catch (Exception e)
            {
                LogManager.Write("PSSService.ExchangeScore:" + e.Message);
                return null;
            }
        }

        [OperationContract]
        public string UnExchangeScore(int ID)
        {
            try
            {
                lock (this)
                {
                    this.Authoricate();
                    using (PSSDataClassesDataContext context = new PSSDataClassesDataContext())
                    {
                        var query = from q in context.PSS_Score
                                    where q.ID == ID
                                    select q;
                        if (query.Any())
                        {
                            if (query.First().Score < 0)
                            {
                                context.PSS_Score.DeleteOnSubmit(query.First());
                                context.SubmitChanges();
                            }
                            return string.Empty;
                        }
                        return "兑换记录不存在，请重新查询。";
                    }
                }
            }
            catch (Exception e)
            {
                LogManager.Write("PSSService.UnExchangeScore:" + e.Message);
                return null;
            }
        }
        #endregion
    }

    //Device_ID = e.DeviceID,
    //                   Price = (int)(e.Price) * 100,
    //                   Total = e.Total,
    //                   Fee_Pack = (short)e.FeePack,
    //                   Remark = e.Remark
    [Serializable]
    public class VW_OrderedDevice
    {
        public int Device_ID
        { get; set; }
        /// <summary>
        /// 分
        /// </summary>
        public int Price
        {
            get;
            set;
        }
        public int Total
        { get; set; }
        public short Fee_Pack
        {
            get;
            set;
        }
        public string Remark
        {
            set;
            get;
        }
    }
    [Serializable]
    public enum OrderDuration
    {
        Next,
        Rollback,
        Send,
        Deny
    }

    [Serializable]
    public  class UnpurchaseIMEI
    {
        public string IMEI;
        public short ProviderID;
        public int DeviceID;
        public string DeviceName;
        public DateTime OrderTime;
        public decimal Price;
    }

    [Serializable]
    public class PayResult
    {
        public string Message;
        public int TotalScore;
    }
}
